package com.javaziliao.design.adapter;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javaziliao.design.pojo.UserInfo;
import com.javaziliao.design.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 第三方登录适配器，继承复用并扩展功能
 */
@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget {
    @Value("${gitee.state}")
    private String giteeState;
    @Value("${gitee.token.url}")
    private String giteeTokenUrl;
    @Value("${gitee.user.url}")
    private String giteeUserUrl;
    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;

    @Override
    public String loginByGitee(String code, String state) {
        // 授权码换取token
        String result = HttpUtil.post(giteeTokenUrl.concat(code), "");
        try {
            System.out.println(result);
            JSONObject jsonObject = JSON.parseObject(result);
            String accessToken = Convert.toStr(jsonObject.get("access_token"));
            String userResult = HttpUtil.get(giteeUserUrl.concat(accessToken));
            JSONObject userObject = JSON.parseObject(userResult);
            String userName = giteeUserPrefix.concat(Convert.toStr(userObject.get("login")));
            String password = userName;
            return autoRegister3rdAndLogin(userName, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String autoRegister3rdAndLogin(String userName, String password) {
        if (super.checkUserExists(userName)){
            return super.login(userName,password);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());
        super.register(userInfo);
        return super.login(userName,password);
    }

    @Override
    public String loginByWechat(String... params) {
        return null;
    }

    @Override
    public String loginByQQ(String... params) {
        return null;
    }
}
